<template>
  <div
    class="page-mobile-study-situation"
    :class="[action == 'complete-test' ? 'complete_test' : '']"
  >
    <white-header
      :isShowTopNav="true"
      :isShowBack="true"
      :isShowRight="true"
      :title="title"
    ></white-header>
    <div class="course_list" v-if="courseAction.includes(action)">
      <div
        class="course-remind"
        :class="[study_course_list.length == index + 1 ? 'unbottomline' : '']"
        v-for="(item, index) in study_course_list"
        :key="index"
      >
        <div class="remind-left">
          <img :src="item.iconPath" alt="" />
        </div>
        <div class="remind-right">
          <div class="course-name">
            {{ item.acName }}《{{ item.courseName }}》
          </div>
          <div class="card-info" style="margin:10px 0;display:flex;">
            <van-progress
              style="width:80%"
              :percentage="Math.ceil(item.schedule * 100)"
              color="var(--theme-color)"
              :show-pivot="false"
            /><span style="margin-left:10px;line-height: 0.2;"
              >{{ Math.ceil(item.schedule * 100) }}%</span
            >
          </div>
        </div>
      </div>
      <div class="footer" v-show="study_course_list.length != 0">
        <span class="tips">我是有底线的</span>
      </div>
      <van-empty
        :description="$t('locale.mobile.course.t2')"
        v-if="study_course_list.length == 0"
      />
    </div>
    <div class="test-list" v-if="testAction.includes(action)">
      <div
        class="test-item"
        v-for="(item, index) in study_test_list"
        :key="index"
      >
        <img
          class="logo-tips"
          :src="
            isTestStart(item.examinationStartDate)
              ? '/img/mobile/question_analog_start.png'
              : '/img/mobile/question_analog_notstart.png'
          "
          alt=""
        />
        <div class="paper-name">{{ item.name }}</div>
        <div class="paper-info">
          <span>题数：{{ item.itemList.length }}道</span>
          <span class="line">|</span>
          <span>限时：{{ item.span }}分钟</span>
          <span class="line">|</span>
          <span>满分：{{ item.total }}分</span>
        </div>
        <div class="paper-time">
          <img src="/img/mobile/paper-time.png" alt="" />
          <span
            >考试时间：{{ formatTime(item.examinationStartDate) }} -
            {{ formatTime(item.examinationDeadlineDate) }}</span
          >
        </div>
      </div>
      <div class="footer" v-show="study_test_list.length != 0">
        <span class="tips">我是有底线的</span>
      </div>
      <van-empty description="暂无考试" v-show="study_test_list.length == 0" />
    </div>

    <div class="done-paper" v-if="action == 'complete-test'">
      <div
        class="test-record"
        v-for="(item, index) in done_paper_list"
        :key="index"
        @click="toPath('/m/test-log?paper_id='+item.paperId+'&test_log_id='+item.id)"
      >
        <div class="paper-name">
          <div class="name-left">{{ item.paperName }}</div>
          <div class="name-right" :class="[is_pass(item) ? 'green' : 'red']">
            {{ is_pass(item) ? "及格" : "不及格" }}
          </div>
        </div>
        <div class="paper-time">
          <div class="time-left">
            考试时间：{{ formatTime(item.createTime) }}
          </div>
          <div class="time-right">
            <span style="font-size:.4608rem;">{{ item.score }}</span
            >分
          </div>
        </div>
      </div>
      <div class="footer" v-show="done_paper_list.length != 0">
        <span class="tips">我是有底线的</span>
      </div>
      <van-empty description="暂无记录" v-show="done_paper_list.length == 0" />
    </div>
  </div>
</template>

<script>
import CourseCard from "~/components/mobile/CourseCard.vue";
import WhiteHeader from "~/components/mobile/WhiteHeader.vue";
import { getMyOrderList } from "~/api/order";
import { getMemberInfo, getMember } from "~/api/member";
import { getUserTestPaper, paperTestList } from "~/api/test";
import { mapState, mapActions, mapMutations } from "vuex";
export default {
  props: ["setDisabled", "refreshFun", "setLoading"],
  components: {
    CourseCard,
    WhiteHeader
  },
  data() {
    return {
      //考试记录分页
      page: 1,
      pageSize: 10,
      total: 0,
      course_list: [],//个人购买课程列表
      test_list: [],//个人考试列表（未考，正在考）
      done_paper_list: [],//已考完试卷记录列表
      memberDiscount: {},//会员折扣
      courseAction: ["notstart-course", "learning-course", "complete-course"],
      testAction: ["notstart-test", "learning-test"],
      action: "",
      title: "",
      scroll_heigth:0,
    };
  },
  computed: {
    ...mapState({
      token(state) {
        return state.token;
      },
      user_info(state) {
        return state.user_info;
      },
      class_list(state) {
        return state.class_list;
      },
      is_loading(state) {
        return state.is_loading;
      },
      is_member(state) {
        return JSON.stringify(state.member_info) != "{}";
      },
      user_member(state) {
        return state.member_info;
      }
    }),
    study_course_list() {
      if (this.action == "notstart-course") {
        return this.course_list.filter(item => item.schedule === 0);
      } else if (this.action == "learning-course") {
        return this.course_list.filter(
          item => item.schedule > 0 && item.schedule < 1
        );
      } else if (this.action == "complete-course") {
        return this.course_list.filter(item => item.schedule === 1);
      }else{
        return [];
      }
    },
    study_test_list() {
      if (this.action == "notstart-test") {
        return this.test_list.filter(
          item => !this.isTestStart(item.examinationStartDate)
        );
      } else if (this.action == "learning-test") {
        return this.test_list.filter(item =>
          this.isTestStart(item.examinationStartDate)
        );
      }else{
        return [];
      }
    }
  },
  watch: {},
  methods: {
    ...mapMutations(["SET_IS_LOADING"]),
    ...mapActions(["initMajorList", "initClassList", "initMember"]),
    toPath(path) {
      this.$router.push(path);
    },
    //判断考试是否合格
    is_pass(item) {
      if (!item.score) {
        return false;
      } else {
        if (item.score < item.passScore) {
          return false;
        } else {
          return true;
        }
      }
    },
    //获取会员信息
    async getMemberInfo() {
      this.SET_IS_LOADING(true);
      if (this.token && Object.keys(this.user_info).length > 0) {
        let memberDiscount = await getMemberInfo(this.user_info.id);
        if (
          memberDiscount &&
          memberDiscount.data &&
          memberDiscount.data.code == 200
        ) {
          this.memberDiscount = memberDiscount.data.data;
        } else {
          
        }
      }

      this.SET_IS_LOADING(false);
    },
    //格式化时间
    formatTime(timestamp) {
      var newTime = new Date(timestamp);
      var y = newTime.getFullYear();
      var m = newTime.getMonth() + 1;
      var d = newTime.getDate();
      var add0 = m => {
        return m < 10 ? "0" + m : m;
      };
      return add0(y) + "年" + add0(m) + "月" + add0(d) + "日";
    },
    //判断考试是否开始
    isTestStart(timestamp) {
      return timestamp < new Date().getTime();
    },
    //拿到用户所有考试试卷
    async getTestList() {
      this.SET_IS_LOADING(true);
      let result = await getUserTestPaper({ userId: this.user_info.id });
      if (result && result.data && result.data.code == 200) {
        console.log("终极试卷", result.data.data);
        this.test_list = result.data.data;
      } else {
        
      }
      this.SET_IS_LOADING(false);
    },
    //拿到购买的课程列表
    async getMyOrderList() {
      this.SET_IS_LOADING(true);
      let params = {
        userId: this.user_info.id
      };
      let result = await getMyOrderList(params);
      if (result && result.data && result.data.code == 200) {
        this.course_list = result.data.data.rows;
      } else {
        this.SET_IS_LOADING(false);
        this.$toast(
          this.$t("locale.mobile.index.t9"),
          result && result.data && result.data.msg
        );
      }
      this.SET_IS_LOADING(false);
    },
    //获取数据，只有考试记录需要分页
    async getData(fetch_type) {
      return new Promise(async (resolve, reject) => {
        this.SET_IS_LOADING(true);
        if (this.courseAction.includes(this.action)) {
          this.getMyOrderList();
        } else if (this.testAction.includes(this.action)) {
          this.getTestList();
        } else if (this.action === "complete-test") {
          this.SET_IS_LOADING(true);
          let result = await paperTestList({
            userId: this.user_info.id,
            sort: "id desc",
            offset: this.pageSize * (this.page - 1),
            limit: this.pageSize
          });
          if (result && result.data && result.data.code == 200) {
            const { data } = result.data;
            if (fetch_type == "pullup") {
              this.done_paper_list = [...this.done_paper_list, ...data.rows];
            } else {
              this.done_paper_list = data.rows;
            }
            this.total = data.total;
          } else {
            this.$toast(
              this.$t("locale.mobile.testRecord.t4") + result &&
                result.data &&
                result.data.msg
            );
            this.SET_IS_LOADING(false);
          }
          this.SET_IS_LOADING(false);
        }
      })
        .then()
        .catch(e => {
          this.SET_IS_LOADING(false);
        });
    },
    //初始化页面
    initPage() {
      return new Promise((res, rej) => {
        if (process.client) {
          try {
            this.action = this.$route.query.action;
            if (this.action == "notstart-course") {
              this.title = "尚未学习";
              //   this.title = "即将开课";
            } else if (this.action == "learning-course") {
              this.title = "正在学习";
            } else if (this.action == "complete-course") {
              this.title = "完成课程";
            } else if (this.action == "notstart-test") {
              this.title = "尚未开考";
            } else if (this.action == "learning-test") {
              this.title = "正在考试";
            } else if (this.action == "complete-test") {
              this.title = "考试记录";
            }
            this.getData();
            this.getMemberInfo();
            this.initMember();
            res("success");
          } catch (e) {
            console.log(e);
            rej(e);
          }
        }
      }).then();
    },
    throttle(fn, delay) {
      let lastTime = 0;
      return !(function() {
        let nowTime = Date.now();
        if (nowTime - lastTime > delay) {
          fn.call(this);
          lastTime = nowTime;
        }
      })();
    },
    pullUp() {
      // 滚动条离顶部的距离
      let scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop;
      // 窗口可视区域高度
      let clientHeight =
        document.documentElement.clientHeight || document.body.clientHeight;
      // 滚动区域高度
      let scrollHeight =
        document.documentElement.scrollHeight || document.body.scrollHeight;
      // 滚动条 + 可视区域高度 >= 滚动条高度 ==>  滚动条触底
      if (scrollTop + clientHeight >= scrollHeight - 120) {
        console.log("上拉加载");
        if (this.total <= this.done_paper_list.length) {
          return;
        }
        if (this.is_loading) {
          return;
        }
        this.page++;
        this.getData("pullup");
      }
    },
    eventListener() {
      this.throttle(this.pullUp, 30);
    },
    initState() {
      this.page = 1;
      this.pageSize = 10;
      this.total = 0;
    }
  },
  activated() {
    if (process.client) {
      this.$nextTick(() => {
        setTimeout(() => {
          document.body.scrollTop = this.scroll_heigth;
          document.documentElement.scrollTop = this.scroll_heigth;
        }, 0);
      });
      window.addEventListener("scroll", this.eventListener);
      this.initPage();
    }
    this.setDisabled(false);
    this.refreshFun(() => {
      this.initPage()
        .then(res => {
          if (res == "success") {
            this.setLoading(false);
          }
        })
        .catch(() => {
          this.setLoading(false);
          this.SET_IS_LOADING(false);
        });
    });
  },
  deactivated() {
    let scroll_heigth =
      document.documentElement.scrollTop || document.body.scrollTop;
    this.scroll_heigth = scroll_heigth;
    this.initState();
    this.setDisabled(true);
    window.removeEventListener("scroll", this.eventListener);
  },
  beforeDestroy() {
    window.removeEventListener("scroll", this.eventListener);
  },
  created() {
    //开启下拉刷新
    this.setDisabled(false);
    //初始化页面数据
    this.initPage();
    //下拉回调
    this.refreshFun(() => {
      this.initPage()
        .then(res => {
          if (res == "success") {
            this.setLoading(false);
          }
        })
        .catch(() => {
          this.setLoading(false);
          this.SET_IS_LOADING(false);
        });
    });
    //返回上次页面滚动条的位置
    // this.$nextTick(() => {
    //   document.body.scrollTop = this.scroll_heigth;
    //   document.documentElement.scrollTop = this.scroll_heigth;
    // });
  },
  mounted() {
    if (process.client) {
      window.addEventListener("scroll", this.eventListener);
    }
  }
};
</script>

<style lang="scss" scoped>
.page-mobile-study-situation {
  //   min-height: calc(100vh - 1.6rem);
  min-height: 100vh;
  .footer {
    padding: 0.3rem;
    font-size: 0.26rem;
    color: #babec2;
    text-align: center;
    .tips {
      position: relative;
    }
    .tips::before {
      content: "";
      display: block;
      position: absolute;
      left: -1.7rem;
      top: 50%;
      transform: translateY(-1px);
      width: 1.5rem;
      height: 1px;
      background: #babec2;
    }
    .tips::after {
      content: "";
      display: block;
      position: absolute;
      right: -1.7rem;
      top: 50%;
      width: 1.5rem;
      transform: translateY(-1px);
      height: 1px;
      background: #babec2;
    }
  }
  .course_list {
    // border-top: 0.026rem solid #f7f7fa;
    .course-remind {
      width: 6.8rem;
      box-sizing: content-box;
      margin: 0 auto;
      height: 2.3rem;
      display: flex;
      align-items: center;
      justify-content: space-between;
      border-bottom: 0.02rem solid #ededf1;
      .remind-left {
        width: 2.592rem;
        height: 1.728rem;
        background: var(--theme-color);
        border-radius: 0.05rem;
        overflow: hidden;
        img {
          width: 100%;
          height: 100%;
          display: block;
        }
      }
      .remind-right {
        width: 4rem;
        height: 1.728rem;
        position: relative;
        .course-name {
          margin-top: 0.1rem;
          font-weight: bold;
          font-size: 0.26rem;
          line-height: 0.35rem;
          height: 1.2rem;
        }
        .card-info {
          display: flex;
          justify-content: space-between;
          align-items: center;
          font-size: 0.24rem;
          .card-info-left {
            display: flex;
            align-items: center;
            color: #adafb3;
            img {
              width: 0.4rem;
              height: 0.4rem;
              display: block;
            }
          }
          .card-info-right {
            // font-size: .34rem;
            font-family: "微软雅黑", arial, "\5b8b\4f53";
            color: var(--theme-color);
            // font-family: -apple-system,BlinkMacSystemFont,Microsoft YaHei UI,Microsoft YaHei,Roboto,Hiragino Sans GB,Source Han Sans CN,Fira Sans,Droid Sans,Helvetica Neue,arial,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol;
            .coursedot {
              // font-size: .26rem;
              margin-right: 0.06rem;
            }
            .price {
            }
            .oldprice {
              color: #666;
              position: relative;
            }
            .oldprice::before {
              content: "";
              display: block;
              position: absolute;
              left: -5%;
              top: 50%;
              transform: translateY(-50%);
              width: 110%;
              height: 0.02rem;
              background: #666;
            }
          }
        }
      }
    }
    .course-remind.unbottomline {
      border-bottom: none;
    }
    .no-more {
      padding: 0.2rem 0 0;
      text-align: center;
      font-size: 0.26rem;
      color: #666;
    }
  }
  .test-list {
    width: 7.2rem;
    .test-item {
      width: 6.62rem;
      height: 2.208rem;
      padding: 0.3rem 0.192rem;
      // margin: .1rem 0;
      margin: 0.192rem auto;
      background-color: #ffffff;
      border-radius: 0.192rem;
      // box-shadow:0 1px 2px rgba(0, 0, 0, .3);
      border: 1px solid #f2f2f2;
      position: relative;
      .logo-tips {
        display: block;
        width: 0.6528rem;
        height: 0.6528rem;
        position: absolute;
        top: 0.1rem;
        right: 0.1rem;
      }
      .paper-name {
        font-size: 0.288rem;
        font-weight: bold;
        color: #4a4b4d;
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
      }
      .paper-info {
        font-size: 0.2304rem;
        font-weight: bold;
        color: #abafb3;
        margin: 0.3rem 0;
        .line {
          margin: 0 0.2rem;
        }
      }
      .paper-time {
        font-size: 0.2304rem;
        font-weight: bold;
        color: #abafb3;
        // margin: .2rem 0;
        display: flex;
        align-items: center;
        img {
          width: 0.2592rem;
          height: 0.2592rem;
          background: var(--theme-color);
          display: block;
          margin-right: 0.1rem;
        }
      }
    }
  }
  .done-paper {
    width: 7.2rem;
    padding-top: 0.384rem;
    .test-record {
      width: 6.624rem;
      height: 2.208rem;
      background-color: #ffffff;
      border-radius: 0.192rem;
      margin: 0rem auto 0.384rem;
      padding: 0.3rem 0.192rem;
      .paper-name {
        font-weight: bold;
        font-size: 0.288rem;
        color: #4a4b4d;
        display: flex;
        justify-content: space-between;
        height: 1rem;
        .name-left {
          width: 5rem;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        .name-right {
          width: 1rem;
          text-align: right;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          &.green {
            color: #84d29f;
          }
          &.red {
            color: #f99797;
          }
        }
      }
      .paper-time {
        font-weight: bold;
        font-size: 0.2304rem;
        color: #4a4b4d;
        display: flex;
        justify-content: space-between;
        align-items: baseline;
        .time-left {
          width: 4.5rem;
        }
        .time-right {
          text-align: right;
          color: var(--theme-color);
          width: 1.5rem;
        }
      }
    }
  }
}
.page-mobile-study-situation.complete_test {
  background: #f7f7fa;
}
</style>
<style lang="scss">
.page-mobile-study-situation {
  .van-popup {
    width: 7.2rem;
  }
}
</style>
